package java流相关;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @author coderFu
 * @create 2022/3/4
 *
 * 管道流
 * java 管道流的定义： 实现两个线程的数据交互
 * 包括四种： 管道字节输入流PipedInputStream 、 管道字节输入流PipedOutPutDStream
 * 管道字符输入流 PipedReader、 管道字符输出流PipedWriter
 *
 * 用户线程之间的通信 ！！！！
 *
 * 进程之间通信的方式: 管道 消息队列 共享内存 FIFO socket PV信号量 解决临界资源的问题
 *
 */
public class PipeStream {

    public static void main(String[] args) throws IOException {
        ThreadA threadA = new ThreadA();
        Thread2 thread2 = new Thread2(threadA);
        threadA.start();
        thread2.start();

    }


}


class ThreadA extends Thread{

    // 创建管道流

    private final PipedOutputStream pipedOutputStream = new PipedOutputStream();

    public PipedOutputStream getOut(){
        return pipedOutputStream;
    }

    @Override
    public void run() {

        try {
            for (int i = 65; i < 65+ 26; i++) {
                pipedOutputStream.write(i);
              //  Thread.sleep(1000);
            }
            pipedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                System.out.println("输出流关闭了吗");
                pipedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

class Thread2 extends Thread{

    private PipedInputStream pipedInputStream = null;

    public Thread2(ThreadA threadA) throws IOException {
        pipedInputStream = new PipedInputStream(threadA.getOut());
    }

    @Override
    public void run() {
            try {
                int len = -1;
                // 此处一直在读，等待这数据过来
                while (true) {
                    if ((len = pipedInputStream.read()) != -1) {
                        System.out.println((char) len);
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    System.out.println("流最后关闭了吗");
                    pipedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

    }

}